<?php


namespace App\Extensions\Actions\Document;

use App\Extensions\Action;
use App\Services\DocumentService;
use Encore\Admin\Actions\Response;
use Encore\Admin\Facades\Admin;
use Illuminate\Contracts\Filesystem\FileNotFoundException;
use Illuminate\Http\Request;


class DocumentUploadPost extends Action
{
    protected $selector = '.document-upload';
    public $name = '上传附件';


    /**
     * @param Request $request
     * @return Response
     * @throws FileNotFoundException
     */
    public function handle(Request $request)
    {
        $user = Admin::user();
        $user_id = $user['id'] == 1 ? 0 : $user['id'];
        $file = $request->file('file');
        DocumentService::getInstance()->addDocument($file, [
            'department_id' => $user['role_type'] == 1 ? 0 : $user['department_id'],
            'slug'          => $request->get('slug') ?: null,
            'type'          => $request->get('type') ?: 0,
            'name'          => $request->get('name') ?: $file->getClientOriginalName()
        ], $user_id);
        return $this->response()->success('操作成功')->refresh();
    }

    public function form()
    {
        $this->file('file', '请选择文件')->rules('required', ['required' => '请选择附件']);
    }

    public function html()
    {
        return <<<HTML
        <a class="btn btn-sm btn-default document-upload">{$this->name()}</a>
HTML;
    }

}
